<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class MY_Model extends CI_Model {

	var $_table;
	var $_primary_id_name = 'id';//默认主键ID名称
	var $debug = true;
	
    function __construct()
    {
        parent::__construct();
    }

    /**
     * @param $where eg： array('name !=' => $name, 'id <' => $id, 'date >' => $date);
     * @return 条数
     */
    function count($where=array(1=>1)){
    	$this->db->where($where);
		$this->db->from($this->_table);
		return $this->db->count_all_results();
    }

	function selectByParam($where=array(1=>1),$order_by=null) {
		$this->db->where($where);
		if($order_by)
			$this->db->order_by($order_by);
		$result = $this->db->get($this->_table);
    	return $result->result_array();
    }
    
    function selectAll() {
    	$data = $this->db->query('select * from '.$this->_table);
    	return $data->result_array();
    }
    
    function selectById($id) {
    	$result = $this->db->query('select * from '.$this->_table.' where '.$this->_primary_id_name.'='.$id);
    	return $result->row_array();
    }
    /*
     * $ids eg:1,2,3,4
     */
    function selectByIds($ids) {
    	$result = $this->db->query('select * from '.$this->_table.' where '.$this->_primary_id_name.' in('.$ids.')');
    	return $result->result_array();
    }
 
    function select($index=1,$size=20){
    	$total = $this->db->query('select count(*) as count from '.$this->_table);
    	$data = $this->db->query('select * from '.$this->_table.' limit '.($index - 1)*$size.','.$size);
    	$result['total'] = $total->row()->count;
    	$result['data'] = $data->result_array();
    	return $result;
    }
    
	function insert($data) {
    	$this->db->insert($this->_table,$data);
    	return $this->db->insert_id();
    }
    
    function update($data){
    	$this->db->where($this->_primary_id_name, $data[$this->_primary_id_name]);
//    	unset($data->id);  
//		reset($data);
    	$this->db->update($this->_table,$data);
    	return $this->db->affected_rows();
    }
    
    function delete($id) {
    	$this->db->where($this->_primary_id_name, $id);
		$this->db->delete($this->_table);
		return $this->db->affected_rows();
    }
    
    function deleteByIds($ids){
    	$this->db->where_in($this->_primary_id_name, $ids);
		$this->db->delete($this->_table); 
		return $this->db->affected_rows();
    }
    
}
?>